const path = require('path');
const url = require('url');
const electron = require('electron');
const {
    app,
    BrowserWindow,
    ipcMain
} = require('electron');
const { autoUpdater } = require('electron-updater');
const feedUrl = `http://127.0.0.1:8080/${process.platform}`;

app.disableHardwareAcceleration()
let webContents;

let createWindow = () => {
    let win = new BrowserWindow({
        width: 3440,
        height: 368,
        x:0,
        y:0,
        id:"1",
        fullscreen:false,
        webPreferences: {
            devTools: false
        }
    });

    webContents = win.webContents;

    win.loadURL(
        url.format({
            pathname: path.join(__dirname, 'src/index.html'),
            protocol: 'file:',
            slashes: true
        })
    );
    win.webContents.on('paint', (event, dirty, image) => {
      // updateBitmap(dirty, image.getBitmap())
    })
    win.webContents.setFrameRate(30)
    win.setVisibleOnAllWorkspaces(true) 
    // webContents.openDevTools();
};

let sendUpdateMessage = (message, data) => {
    webContents.send('message', { message, data });
};

let checkForUpdates = () => {
	return true;
    autoUpdater.setFeedURL(feedUrl);

    autoUpdater.on('error', function (message) {
        sendUpdateMessage('error', message)
    });
    autoUpdater.on('checking-for-update', function (message) {
        sendUpdateMessage('checking-for-update', message)
    });
    autoUpdater.on('update-available', function (message) {
        sendUpdateMessage('update-available', message)
    });
    autoUpdater.on('update-not-available', function (message) {
        sendUpdateMessage('update-not-available', message)
    });

    // 更新下载进度事件
    autoUpdater.on('download-progress', function (progressObj) {
        sendUpdateMessage('downloadProgress', progressObj)
    })
    autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
        ipcMain.on('updateNow', (e, arg) => {
            //some code here to handle event
            autoUpdater.quitAndInstall();
        })
        sendUpdateMessage('isUpdateNow');
    });

    //执行自动更新检查
    autoUpdater.checkForUpdates();
};


app.on('ready', () => {
     createWindow();
        setTimeout(checkForUpdates, 1000);
    let displays = electron.screen.getAllDisplays()
    let externalDisplay = displays.find((display) => {
      return display.bounds.x !== 0 || display.bounds.y !== 0
    })
  
    if (externalDisplay) {
      win = new BrowserWindow({
        x: externalDisplay.bounds.x + 50,
        y: externalDisplay.bounds.y + 50
      })
      win.loadURL('http://www.163.com')
    }
  })
app.on('window-all-closed', () => app.quit());